package com.gaojiawei.multiThread09_ReetrantReadWriteLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * demo
 */
public class L01_ReetrantReadWriteLockDemo {
    //def ReetrantReadWriteLock
    static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    //def read lock
    static ReentrantReadWriteLock.ReadLock readLock =  reentrantReadWriteLock.readLock();

    //def write lock
    static ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    public static void main(String[] args) {
        new Thread(()->{
            //add read lock
            readLock.lock();
            try {
                System.out.println("thread 1 have readlock");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                readLock.unlock();
            }
        }).start();

        new Thread(()->{
            readLock.lock();
            try {
                System.out.println("thread b has read lock");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                readLock.unlock();
            }
        }).start();

        new Thread(()->{
            writeLock.lock();
            try {
                System.out.println("thread c has write lock");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                writeLock.unlock();
            }
        }).start();

    }
}
